<?php

namespace App\Libraries\Entities;

use Auth;

trait HasUpdated
{
    protected $UpdatedFlag = MonitoringMode::None;

    public function setUpdated()
    {
        if ($this->hasUpdatedAt()) {
            $this->setUpdatedAt($this->freshTimestamp());
        }
        if ($this->hasUpdatedUserId()) {
            $this->setUpdatedUserId();
        }
    }

    public function hasUpdatedAt()
    {
        $flag = !is_null(static::UPDATED_AT) && !$this->isDirty(static::UPDATED_AT);
        $flag = $flag && (MonitoringMode::OnlyTime === $this->UpdatedFlag || MonitoringMode::All === $this->UpdatedFlag);

        return $flag;

        // return !is_null(static::UPDATED_AT) && !$this->isDirty(static::UPDATED_AT) && $this->useUpdated();
    }

    public function useUpdated()
    {
        return MonitoringMode::None !== $this->UpdatedFlag;
    }

    public function hasUpdatedUserId()
    {
        $flag = !is_null(static::UPDATED_USER_ID) && !$this->isDirty(static::UPDATED_USER_ID);
        $flag = $flag && (MonitoringMode::OnlyUser === $this->UpdatedFlag || MonitoringMode::All === $this->UpdatedFlag);

        return $flag;
        // return !is_null(static::UPDATED_USER_ID) && !$this->isDirty(static::UPDATED_USER_ID) && $this->useUpdated();
    }

    protected function setUpdatedUserId()
    {
        $this->{static::UPDATED_USER_ID} = Auth::user() ? Auth::user()->user_id : '';
    }
}
